package com.extremelylargepackage.entity;

import com.extremelylargepackage.GameResources;

public class AiRandomMove implements AiMoveComponent
{
	private Enemy _me;
	private long _timeUntilNextMove;
	private boolean _finished;
	private boolean _fleeing;
	private long _elapsedTimeAlive;
	
	private float _fleeTime;
	//In seconds, how often enemy changes direction
	private float _minFrequency;
	private float _maxFrequency;
	
	public AiRandomMove(float fleeTime, float minFrequency, float maxFrequency)
	{
		_fleeTime = fleeTime;
		_minFrequency = minFrequency;
		_maxFrequency = maxFrequency;
		_timeUntilNextMove = 0;
		_finished = false;
	}
	
	@Override
	public void setSelf(Enemy me) 
	{
		_me = me;
	}

	@Override
	public void performMove(long time) 
	{
		_elapsedTimeAlive += time;
		if((!_finished && !_fleeing && _timeUntilNextMove <= 0) || (!_fleeing && _me._dirX == 0 && _me._dirY == 0))
		{
			_me._dirX = ((float)(Math.random() * GameResources.SCREEN_WIDTH)) - _me._locX;
			_me._dirY = ((float)(Math.random() * GameResources.SCREEN_HEIGHT * .75)) - _me._locY;
			float mod = _maxFrequency - _minFrequency;
			mod *= Math.random();
			_timeUntilNextMove = (long)((mod + _minFrequency)*1000);
			if(_elapsedTimeAlive >= _fleeTime*1000)
			{
				if(_me._dirX > 0)
					_me._dirX = GameResources.SCREEN_WIDTH * 1.5f;
				else
					_me._dirX = GameResources.SCREEN_WIDTH * -1.5f;
				
				if(_me._dirY > 0)
					_me._dirY = GameResources.SCREEN_HEIGHT * 1.5f;
				else
					_me._dirY = GameResources.SCREEN_HEIGHT * -1.5f;
				
				_fleeing = true;
			}
		}
		else if(_fleeing && (_me._locX + _me.getWidth() < 0 || _me._locX > GameResources.SCREEN_WIDTH
				|| _me._locY + _me.getHeight() < 0 || _me._locY > GameResources.SCREEN_HEIGHT))
		{
			_finished = true;
		}
		else
		{
			_timeUntilNextMove -= time;
		}
	}

	@Override
	public boolean finished() 
	{
		return _finished;
	}
	
	public Object clone()
	{
		return new AiRandomMove(_fleeTime, _minFrequency, _maxFrequency);
	}

}
